package com.example.servicedemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class Activity3 extends AppCompatActivity {

    private static final String TAG = "Activity3";

    // 给Service，让Service给Activity发送消息的
    private Messenger activityMessenger = new Messenger(new MyHandler());

    // 用来给Service发送消息的
    private Messenger messenger;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        // 绑定
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            messenger = new Messenger(service);
            Log.i(TAG, "绑定");
        }
        // 解绑
        @Override
        public void onServiceDisconnected(ComponentName name) {
            messenger = null;
            Log.i(TAG, "解绑");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_3);

        // 启动绑定服务
        findViewById(R.id.button_startAndBind).setOnClickListener(v -> {
            startService(new Intent(this, MyService3.class));
            // 绑定的时候，将activityMessenger传过去
            Intent intent = new Intent(this, MyService3.class);
            intent.putExtra("messenger", activityMessenger);
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        });
        // 发送消息给Service
        findViewById(R.id.button_sendMsgToService).setOnClickListener(v -> {
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 0;
                message.obj = "对象";
                message.arg1 = 11;
                message.arg2 = 22;
                try {
                    messenger.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static class MyHandler extends Handler {
        // 处理消息（Activity接收到的）
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage:" + msg);
            // 根据不同的消息处理
            switch (msg.what) {

            }

        }
    }
}